from sys import exit
from pygame import init
from pygame import event as pe
from pygame import display as pdis
from pygame import key as pk
from pygame.constants import QUIT
from pygame.locals import K_ESCAPE
from pygame import mouse as pm
from pygame import time as pt
from config import ftp

from config import win_size , win_name

init ( )
screen = pdis.set_mode ( win_size )
pdis.set_caption ( win_name )
scenes = [ ]


class ZScreen ( object ) :
    def __init__ ( self ) :
        super ( ZScreen , self ).__init__ ( )
        self.running = True
        self.rect = pdis.get_surface ( ).get_rect ( )
        self.Clock = pt.Clock ( )

    def draw ( self ) :
        while True :
            ticks = self.Clock.tick ( ftp )
            self.__draw ( )
            for event in pe.get ( ) :
                keys = pk.get_pressed ( )
                m_keys = pm.get_pressed ( )
                m_pos = pm.get_pos ( )
                self.__update ( event , keys , m_keys , m_pos )
            pdis.update ( )

    def run ( self ) :
        if self.running :
            self.draw ( )

    def __draw ( self ) :
        screen.fill ( 0 )
        if scenes :
            for x in scenes :
                x.draw ( )

    def __update ( self , event , keys , m_keys , m_pos ) :
        if self.running :
            self.__exit ( event , keys )
            self.__children_update ( event , keys , m_keys , m_pos )

    def __children_update ( self , event , keys , m_keys , m_pos ) :
        if scenes :
            for x in scenes :
                x.update ( event , keys , m_keys , m_pos )

    def __exit ( self , event , keys ) :
        if event.type == QUIT :
            exit ( )
        if keys [ K_ESCAPE ] :
            exit ( )

    def add ( self , *scene ) :
        if scene :
            for x in scene :
                scenes.append ( x )

    def clear ( self ) :
        scenes = [ ]

    @property
    def _size ( self ) :
        return self.rect.size

    @_size.getter
    def _size ( self ) :
        return self.rect.size

    @_size.setter
    def _size ( self , size ) :
        self.rect.size = size

    @property
    def _pos ( self ) :
        return self.rect.topleft

    @_pos.getter
    def _pos ( self ) :
        return self.rect.topleft

    @_pos.setter
    def _pos ( self , pos ) :
        if self.father :
            self.rect.topleft = map ( lambda (a , b ) : a + b , zip ( self.father._pos , pos ) )
